const { getUserCollections, patchUserCollection } = require('../../utils/request');

Page({
  data: {
    activeTab: 0,           // 当前激活的tab
    favoritesList: [],       // 收藏列表数据
    loading: true,          // 加载状态
    refreshing: false,      // 下拉刷新状态
    hasMore: true,          // 是否有更多数据
    currentPage: 1,         // 当前页码
    pageSize: 5,           // 每页数据量
    totalPages: 0,          // 总页数
    showPageControls: false,// 是否显示分页控件
    showCollectionPopup: false, // 是否显示收藏弹窗
    currentItem: null,      // 当前操作的收藏项
    subjectTypes: [         // 分类映射
      { id: 0, name: '书籍', type: 1 },
      { id: 1, name: '动画', type: 2 },
      { id: 2, name: '音乐', type: 3 },
      { id: 3, name: '游戏', type: 4 },
      { id: 4, name: '三次元', type: 6 }
    ]
  },

  // 页面加载时初始化数据
  onLoad() {
    this.loadFavorites();
  },

  onShow() {
    if (this.getTabBar) {
      this.getTabBar().init();
    }
  },

  // 加载收藏数据
  async loadFavorites() {
    const { activeTab, currentPage, pageSize, subjectTypes } = this.data;
    this.setData({ loading: true });
    
    try {
      const subjectType = subjectTypes[activeTab].type;
      const username = wx.getStorageSync('username');
      const res = await getUserCollections(
        username, 
        subjectType,
        null,
        pageSize,
        (currentPage - 1) * pageSize
      );
  
      const formattedData = res.data.map(item => {
        const subject = item.subject || {};
        return {
          id: item.subject_id,
          title: subject.name_cn || subject.name,
          alias: subject.name,
          cover: subject.images?.medium || '/images/default-cover.jpg',
          infoItems: [
            `类型: ${this.getTypeName(subject.type)}`,
            `收藏人数: ${subject.collection_total || 0}`,
            `${this.formatTime(item.updated_at)}`
          ],
          rank: subject.rank || '',
          ratingScore: subject.score || 0,
          ratingTotal: subject.collection_total || 0,
          collection: this.mapCollectionType(item.type),
          roast: item.comment || '',
          isPrivate: item.private,
          time: this.formatTime(item.updated_at)
        };
      });
  
      const totalPages = Math.ceil(res.total / pageSize);
      
      this.setData({
        favoritesList: formattedData,
        loading: false,
        totalPages,
        showPageControls: totalPages > 1,
        hasMore: currentPage < totalPages
      });
    } catch (error) {
      console.error('加载收藏失败:', error);
      wx.showToast({
        title: '加载收藏失败',
        icon: 'none'
      });
      this.setData({
        loading: false
      });
    }
  },

  // 获取类型名称
  getTypeName(type) {
    const types = {
      1: '书籍',
      2: '动画',
      3: '音乐',
      4: '游戏',
      6: '三次元'
    };
    return types[type] || '未知';
  },

  // 映射收藏状态
  mapCollectionType(type) {
    const map = {
      1: 'wish',
      2: 'collect',
      3: 'doing',
      4: 'on_hold',
      5: 'dropped'
    };
    return map[type] || 'default';
  },

  // 反向映射收藏状态
  reverseMapCollectionType(type) {
    const map = {
      'wish': 1,
      'collect': 2,
      'doing': 3,
      'on_hold': 4,
      'dropped': 5
    };
    return map[type] || 0;
  },

  // 格式化时间
  formatTime(timeStr) {
    const date = new Date(timeStr);
    return `收藏于 ${date.getMonth() + 1}月${date.getDate()}日`;
  },

  // 切换tab事件
  onTabChange(e) {
    const activeTab = e.detail.index;
    this.setData({
      activeTab,
      currentPage: 1,
      hasMore: true,
      favoritesList: []
    });
    this.loadFavorites();
  },



  // 下拉刷新
  onRefresh() {
    this.setData({
      refreshing: true,
      page: 1,
      favoritesList: [],
      hasMore: true
    }, () => {
      this.loadFavorites().finally(() => {
        this.setData({ refreshing: false });
      });
    });
  },

  // 点击卡片事件
  onItemClick(e) {
    const itemData = e.detail.itemData;
    wx.navigateTo({
      url: `/pages/item-detail/item-detail?id=${itemData.id}`
    });
  },

  // 显示收藏状态弹窗
  showCollectionPopup(e) {
    const itemData = e.detail.itemData;
    this.setData({
      currentItem: itemData,
      showCollectionPopup: true
    });
  },

  // 隐藏收藏状态弹窗
  hideCollectionPopup() {
    this.setData({
      showCollectionPopup: false
    });
  },

  // 更新收藏状态
  async updateCollectionStatus(e) {
    const formData = e.detail.formData;
    const { currentItem } = this.data;
    
    try {
      const payload = {
        type: formData.collection.number,
        rate: formData.ratingScore,
        comment: formData.roast,
        private: formData.isPrivate
      };

      await patchUserCollection(currentItem.id, payload);
      
      // 更新本地数据
      const updatedList = this.data.favoritesList.map(item => {
        if (item.id === currentItem.id) {
          return {
            ...item,
            collection: formData.collection,
            ratingScore: formData.ratingScore,
            roast: formData.roast,
            isPrivate: formData.isPrivate
          };
        }
        return item;
      });

      this.setData({
        favoritesList: updatedList,
        showCollectionPopup: false
      });

      // 显示操作成功提示
      const statusMap = {
        'wish': '想看',
        'collect': '看过',
        'doing': '在看',
        'on_hold': '搁置',
        'dropped': '弃置'
      };
      
      wx.showToast({
        title: `${currentItem.title} 已标记为 ${statusMap[formData.collection]}`,
        icon: 'success'
      });
    } catch (error) {
      console.error('更新收藏状态失败:', error);
      wx.showToast({
        title: '更新收藏状态失败',
        icon: 'none'
      });
    }
  },

  // 跳转到指定页
  goToPage(page) {
    if (page < 1 || page > this.data.totalPages || page === this.data.currentPage) return;
    
    this.setData({
      currentPage: page,
      favoritesList: []
    });
    this.loadFavorites();
  },

  // 上一页
  prevPage() {
    this.goToPage(this.data.currentPage - 1);
  },

  // 下一页
  nextPage() {
    this.goToPage(this.data.currentPage + 1);
  }
});